package com.scale.service.conversation.controller;

import com.example.common.result.Result;
import com.example.conversation.dto.SendMessageDTO;
import com.example.conversation.vo.MessageVO;
import com.scale.service.conversation.service.ConversationsService;
import com.scale.service.conversation.service.MessagesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 对话会话表 前端控制器
 * </p>
 *
 * @author crp
 * @since 2025-09-24
 */
@Api(tags = "对话管理")
@RestController
@RequestMapping("/api/conversations")
@CrossOrigin(origins = {
    "http://localhost:3000", 
    "http://127.0.0.1:3000", 
    "http://localhost:3001", 
    "http://127.0.0.1:3001", 
    "http://localhost:5173", 
    "http://127.0.0.1:5173"
}, maxAge = 3600, allowedHeaders = "*", allowCredentials = "true")
public class ConversationsController {

    @Autowired
    private ConversationsService conversationsService;
    
    @Autowired
    private MessagesService messagesService;

    /**
     * 获取聊天记录
     */
    @ApiOperation("获取聊天记录")
    @GetMapping("/{characterId}")
    public Result<List<MessageVO>> getChatHistory(
            @ApiParam("角色ID") @PathVariable Long characterId,
            @ApiParam("用户ID") @RequestParam Long userId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size) {
        
        List<MessageVO> messages = messagesService.getChatHistory(characterId, userId, page, size);
        return Result.success(messages);
    }

    /**
     * 发送消息并获取AI回复
     */
    @ApiOperation("发送消息并获取AI回复")
    @PostMapping("/send")
    public Result<MessageVO> sendMessage(
            @ApiParam("发送消息请求") @RequestBody @Validated SendMessageDTO sendMessageDTO,
            @ApiParam("用户ID") @RequestParam Long userId) {
        
        MessageVO aiReply = messagesService.sendMessageAndGetReply(sendMessageDTO, userId);
        return Result.success(aiReply);
    }
}

